import time
import string
import re
import os

class CVersionFile(object):
    '''version file base class'''
    name = ''
    def __init__(self, path):
        self.path = path

    def SetConfig(self, config):
        self.config = config

    def GetFileName(self):
        return os.path.join(self.path, self.name)

    def Change(self):
        pass

class CVfSgold(CVersionFile):
    '''Sgold version file: sib.c'''

    name = "sib.c"
    def __init__(self, path):
        CVersionFile.__init__(self, path)


    def Change(self):
        f = file(self.path+os.sep+CVfSgold.name)
        tmpf = file(self.path+os.sep+"bak_"+CVfSgold.name, 'w')
        for line in f:
            if self.config.sgold_ver_high != '' and \
                    self.config.sgold_ver_low != '' and \
                    self.config.sgold_ver_type != '':
                #change version high
                if re.match("#define.*HIGH.*\"$",line) :
                    line=re.sub(r'".*"', r'"%s"'% self.config.sgold_ver_high, line)
                #change version low
                elif re.match("#define.*LOW.*\"$",line) :
                    line=re.sub(r'".*"', r'"%s"'% self.config.sgold_ver_low,line)
                #change version type
                elif re.search(r'"[RID]"',line) :
                    line=re.sub(r'"[RID]"', r'"%s"'% self.config.sgold_ver_type,line)

            #change build date
            if re.search(r'sw_date ',line) :
                line=re.sub(r'".*"', r'"%s"' % time.strftime('%d%m%Y'),line)

            #change model year
            if re.search(r'model_year',line) :
                line=re.sub(r'".*"', r'"%s"' % time.strftime('%Y'),line)

            if self.config.sgold_ver_svn != '':
                #change SVN
                if re.search(r'^ .*VER_sw_version_svn.*;$',line) :
                    line=re.sub(r'".*"', r'"%s"' % self.config.sgold_ver_svn,line)

            tmpf.write(line)
        f.close()
        tmpf.close()

        #write the new content to original file
        f = file(self.path+os.sep+CVfSgold.name,'w')
        tmpf = file(self.path+os.sep+"bak_"+CVfSgold.name)
        data=tmpf.read()
        f.write(data)

        #close all file
        f.close()
        tmpf.close()
        os.remove(self.path+os.sep+"bak_"+CVfSgold.name)

class CVfS12(CVersionFile):
    '''S12 version file: version.h'''

    name = "version.h"
    def __init__(self, path, type):
        CVersionFile.__init__(self, path)
        self.type=type
        self.market = ''

    def SetMarket(self, mkt):
        self.market = mkt

    def ChangeVersionID(self):
        ix = self.verIdIndex
        line = self.lines[ix]
        self.lines[ix]=re.sub(r'".*"',r'"%s"' % self.config.s12_ver_id, line)

    def ChangeSgoldVersion(self):
        ix = self.sgoldVerIndex
        line = self.lines[ix]
        self.lines[ix]= re.sub(r"#define SGOLD_VER_HIGH.*0x[\dA-Fa-f]+", "#define SGOLD_VER_HIGH 0x%02x" % string.atoi(self.config.sgold_ver_high) , line)

        ix += 1
        line = self.lines[ix]
        self.lines[ix] = re.sub(r"#define SGOLD_VER_LOW.*0x[\dA-Fa-f]+", "#define SGOLD_VER_LOW 0x%02x" % string.atoi(self.config.sgold_ver_low) , line)

    def ChangePartNo(self):
        tmpList =[]
        pnList = list(self.config.partNo)
        for c in pnList:
            tmpList.append("'%c'"%c)
        pnStr = string.join(tmpList, ',')

        ix = self.partNoIndex
        line = self.lines[ix]
        self.lines[ix]=re.sub(r"{.*}",r"{%s}"%pnStr,line)

    def GetLineAndOffset(self):
        pass

    def Change(self):
        origFilePN=self.path+os.sep+CVfS12.name
        tmpFilePN=self.path+os.sep+"bak_"+CVfS12.name
        f = file(origFilePN)
        tmpf = file(tmpFilePN, 'w+')

        self.lines = f.readlines()
        self.verIdIndex = 0
        self.sgoldVerIndex = 0
        self.partNoIndex = 0

        self.GetLineAndOffset()

        if self.config.s12_ver_id != '':
            self.ChangeVersionID()

        if self.config.sgold_ver_high != '' and \
                self.config.sgold_ver_low != '':
            self.ChangeSgoldVersion()

        if self.config.partNo != '':
            self.ChangePartNo()


        tmpf.writelines(self.lines)

        f.close()
        tmpf.close()

        #write the new content to original file
        f = file(self.path+os.sep+CVfS12.name,'w')
        tmpf = file(self.path+os.sep+"bak_"+CVfS12.name)
        data=tmpf.read()
        f.write(data)

        #close all file
        f.close()
        tmpf.close()
        os.remove(self.path+os.sep+"bak_"+CVfS12.name)


class CVfS12Infiniti(CVfS12):
    def __init__(self, path):
        super(CVfS12Infiniti, self).__init__(path, "INFINITI")

    def GetLineAndOffset(self):
        #get the line no of key words
        index = 0
        for line in self.lines:
            #to get the ix of search pattern
            if re.search(r"#ifndef S12_RESET_SGOLD_DISABLE",line) :
                self.verIdIndex = index + 1
            elif re.search(r"NISSAN_DCM_INFINITI", line) :
                self.sgoldVerIndex = index + 1
            elif re.search(self.market, line) :
                self.partNoIndex = index + 1
            index += 1

    def ChangeVersionID(self):
        super(CVfS12Infiniti, self).ChangeVersionID()
        ix = self.verIdIndex + 2
        line = self.lines[ix]
        self.lines[ix]=re.sub(r'".*"',r'"%s(NO_WD)"' % self.config.s12_ver_id, line)



class CVfS12EV(CVfS12):
    def __init__(self, path):
        super(CVfS12EV, self).__init__(path, "EV")

    def GetLineAndOffset(self):
        #get the line no of key words
        index = 0
        for line in self.lines:
            #to get the ix of search pattern
            if re.search(r"elif defined \( NISSAN_DCM_EV \)",line) :
                self.verIdIndex = index + 1
                self.sgoldVerIndex = index + 2
            elif re.search(self.market, line) :
                self.partNoIndex = index + 1
            index += 1

class CVfS12EvBcr(CVfS12):
    def __init__(self, path):
        super(CVfS12EvBcr, self).__init__(path, "BCR")

    def GetLineAndOffset(self):
        #get the line no of key words
        index = 0
        for line in self.lines:
            #to get the ix of search pattern
            if re.search(r"elif defined \( NISSAN_DCM_EV \)",line) :
                self.verIdIndex = index + 1
                self.sgoldVerIndex = index + 2
            elif re.search(self.market, line) :
                self.partNoIndex = index + 1
            index += 1

class CVfS12DFL(CVfS12):
    def __init__(self, path):
        super(CVfS12DFL, self).__init__(path, "DFL")

    def GetLineAndOffset(self):
        #get the line no of key words
        index = 0
        for line in self.lines:
            #to get the ix of search pattern
            if re.search(r"if defined \( NISSAN_DCM_DFL \)",line) :
                self.verIdIndex = index + 1
                self.sgoldVerIndex = index + 2
            elif re.search(r"elif defined \( NISSAN_DCM_DFL \)",line) :
                self.partNoIndex = index + 1
            index += 1

class CVfS12NCIC(CVfS12):
    def __init__(self, path):
        super(CVfS12NCIC, self).__init__(path, "NCIC")

    def GetLineAndOffset(self):
        #get the line no of key words
        index = 0
        for line in self.lines:
            #to get the ix of search pattern
            if re.search(r"elif defined \( NISSAN_DCM_NCIC \)",line) :
                self.verIdIndex = index + 1
                self.sgoldVerIndex = index + 2
            elif re.search(r"DCM_PART_NUMBER",line) :
                self.partNoIndex = index
            index += 1

class CVfS12L42L(CVfS12):
    def __init__(self, path):
        super(CVfS12L42L, self).__init__(path, "L42L")

    def GetLineAndOffset(self):
        #get the line no of key words
        index = 0
        for line in self.lines:
            #to get the ix of search pattern
            if re.search(r"elif defined \( NISSAN_DCM_NCIC \)",line) :
                self.verIdIndex = index + 1
                self.sgoldVerIndex = index + 2
            elif re.search(r"DCM_PART_NUMBER",line) :
                self.partNoIndex = index
            index += 1

